const get_db = require('../get_db')
const pug = require('pug')
const utils = require('../utils')

function get_int_auth_token_cache(id, int_auth_token) {
    return new Promise((resolve, reject) => {
        // resolve({ device: 'mock', ip: 'mock' })
        const db = get_db()
        db.int_auth_token_cache.findOne({id,int_auth_token}, (err, doc) => {
            // console.log(doc)
            resolve(doc)
        })
    })
}

function get_user(id) {
    return new Promise((resolve, reject) => {
        // resolve({name: 'mock'})
        const db = get_db()
        db.user.findOne({id}, (err, doc) => {
            // console.log(doc)
            resolve(doc)
        })
    })
}

module.exports = async (ctx, userId) => {
    console.log('#5')
    const body = ctx.request.body
    if (utils.is_empty_object(body) || body.intAuthToken == null || userId == null) {
        ctx.body = { ret: 1001 }
    } else {
        const token = body.intAuthToken
        const matched = await get_int_auth_token_cache(userId, token)
        if (matched != null) {
            const user = await get_user(userId)
            ctx.type = 'text/html'
            ctx.body = pug.compileFile('template/authenticated.pug')({
                device: matched.device,
                ip: matched.ip,
                name: user.name
            })
        } else {
            ctx.body = { err: 'Sorry! The info you provided was wrong' }
        }
    }
}